package com.xw.netty.basic;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * netty服务端
 * @ClassName NettyServer
 * @Author liu zhiyong
 * @Date 2020/8/20 14:53
 * @Version 1.0
 */
public class NettyServer {

    public static void main(String[] args) throws InterruptedException {
        //1.创建一个线程组：接收客户端连接
        EventLoopGroup boosGroup = new NioEventLoopGroup();
        //2.创建一个线程组：处理网络操作
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        //3.创建服务器端启动助手
        ServerBootstrap server = new ServerBootstrap();

        server.group(boosGroup, workerGroup)//4.设置两个线程组
            .channel(NioServerSocketChannel.class)//5.使用NioServerSocketChannel作为服务器端通道的实现
            .option(ChannelOption.SO_BACKLOG, 128)//6.设置线程队列中等待连接的个数
            .childOption(ChannelOption.SO_KEEPALIVE, true)//7.保持活动的连接状态
            .childHandler(new ChannelInitializer<SocketChannel>() {//8.创建通道初始化对象
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {

                    ChannelPipeline pipeline = socketChannel.pipeline();
                    //9.往Pipeline链中添加自定义的业务处理类
                    pipeline.addLast(new NettyServerHandler());
                }
            });

        System.out.println("Server is ready...");

        //绑定端口号
        ChannelFuture future = server.bind(9999).sync();//10.绑定端口bind方法是异步的，但是后面调用搞的sync()方法在主线程main方法里是同步阻塞的，只有连接成功后，才能执行后面的代码
        System.out.println(".........netty server - 启动成功.........");

        //11.关闭通道，关闭线程组
        future.channel().closeFuture().sync();
        boosGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }

}
